package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Filter;


/**
 * @Description:test
 * @Create by: CAt
 * @Date;2021/9/2918:24
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${Tupian.ming}")
    private String tupianming;

    @PostMapping("/upload")
    public R wenjianshangchuan(MultipartFile file) {
        //截取.jsp
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //日志打印
        log.info(substring);
        //生成随机数用uuid
        String aa = UUID.randomUUID().toString() + substring;
        //创建文件夹
        File zz = new File(tupianming);
        //如果不存在
        if (!zz.exists()) {
            //不存在就创建
            zz.mkdir();
        }
        try {
            //给临时文件重新存一个地方
            file.transferTo(new File(tupianming + aa));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(aa);
    }

    @GetMapping("/download")
    public void tupianxiazai(String name, HttpServletResponse response){

        try {
            //输入流  写入图片数据
            FileInputStream fileInputStream=new FileInputStream(new File(tupianming+name));
            //输出流  把图片数据写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //固定写法  图片的格式
            response.setContentType("image/jpeg");

            int len=0;
            byte []arr=new byte[1024];
            while ((len=fileInputStream.read(arr))!=-1){
              outputStream.write(arr,0,len);
              outputStream.flush();
            }
            //关闭流
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
